package cn.like.backEnd.auth;

import cn.hutool.captcha.LineCaptcha;
import cn.like.base.support.exception.BizException;
import cn.like.base.support.exception.code.ExceptionCode;
import cn.like.common.context.redisKey.AuthRedisKey;
import cn.like.redis.RedisKey;
import cn.like.redis.RedisService;
import cn.like.util.CaptchaCreator;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;

/**
 * desc: 验证码服务 <br>
 * details:
 * <pre>
 *     1.生成验证码
 *     2.校验验证码
 *
 * </pre>
 *
 * @author like 980650920@qq.com
 * @date 2021-07-08 14:07:47
 */
@Component
public class CaptchaManager {

    private final RedisService redisService;

    public CaptchaManager(RedisService redisService) {this.redisService = redisService;}

    /**
     * desc: 创建验证码,并且缓存<br>
     *
     * @param key      Key
     * @param response http 响应
     * @return:
     * @author: like 980650920@qq.com
     * @date 2021-07-08 14:06:56
     */
    public void create(String key, HttpServletResponse response) throws Exception {
        final LineCaptcha captcha = CaptchaCreator.getLineCaptcha();

        // 缓存到redis  30s 过期
        redisService.String.setExSec(RedisKey.of(AuthRedisKey.captcha_cache_key,key), captcha.getCode(), 60L);

        // 写回到页面
        captcha.write(response.getOutputStream());
    }

    /**
     * desc: 校验验证码,并删除缓存中的验证码 <br>
     *
     * @param key     Key
     * @param captcha 验证码
     * @return: {@link Boolean }
     * @author: like 980650920@qq.com
     * @date 2021-07-08 15:09:19
     */
    public Boolean valid(String key, String captcha) {
        final String redisKey = RedisKey.of(AuthRedisKey.captcha_cache_key, key);

        // get captcha cache from redis
        final String captchaInCache = redisService.String.get(redisKey);
        // blank，throw ex
        if (StringUtils.isBlank(captchaInCache)) throw new BizException(ExceptionCode.CAPTCHA_IS_NO_VALID);
        // del cache
        redisService.Key.delete(redisKey);

        return captcha.equals(captchaInCache);
    }
}
